package com.dong.binaryTree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author dcz
 * @classname Maxdepth
 * @description 二叉树的最大深度
 * @date 2022/4/14 10:39
 */
public class Maxdepth {
    /**
     * 递归法
     */
    public int maxdepth(TreeNode root){
        if (root == null){
            return 0;
        }
        int leftdepth = maxdepth(root.left);
        int rightdepth = maxdepth(root.right);
        return Math.max(leftdepth,rightdepth) + 1;
    }

    /**
     * 迭代法  层序遍历
     */
    public int maxdepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        int depth = 0;
        while (!deque.isEmpty()){
            int size = deque.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = deque.poll();
                if (poll.left != null){
                    deque.offer(poll.left);
                }
                if (poll.right != null){
                    deque.offer(poll.right);
                }
            }
        }
        return depth;
    }
}
